<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Articulos extends MY_Controller {

  /**
	 * Evita la validacion (enfocado cuando se usa ajax). Ver mas en privilegios_model
	 * @var unknown_type
	 */
	private $excepcion_privilegio = array('ajax_get_siguiente_numero');

	public function _remap($method){
		$this->carabiner->css(array(
				array('bootstrap/bootstrap-simplex.css', 'screen'),
				array('bootstrap/bootstrap-responsive.css', 'screen'),
				array('bootstrap/charisma-app.css', 'screen'),
				array('bootstrap/jquery-ui-1.8.21.custom.css', 'screen'),
				array('bootstrap/fullcalendar.css', 'screen'),
				array('bootstrap/fullcalendar.print.css', 'print'),
				array('bootstrap/chosen.css', 'screen'),
				array('bootstrap/uniform.default.css', 'screen'),
				array('bootstrap/colorbox.css', 'screen'),
				array('bootstrap/jquery.cleditor.css', 'screen'),
				array('bootstrap/jquery.noty.css', 'screen'),
				array('bootstrap/noty_theme_default.css', 'screen'),
				array('bootstrap/elfinder.min.css', 'screen'),
				array('bootstrap/elfinder.theme.css', 'screen'),
				array('bootstrap/jquery.iphone.toggle.css', 'screen'),
				array('bootstrap/opa-icons.css', 'screen'),
				array('bootstrap/uploadify.css', 'screen'),

				array('base-panel.css', 'screen')
		));
		$this->carabiner->js(array(
				array('bootstrap/jquery-1.7.2.min.js'),
				array('bootstrap/jquery-ui-1.8.21.custom.min.js'),
				array('bootstrap/bootstrap-transition.js'),
				array('bootstrap/bootstrap-alert.js'),
				array('bootstrap/bootstrap-modal.js'),
				array('bootstrap/bootstrap-dropdown.js'),
				array('bootstrap/bootstrap-scrollspy.js'),
				array('bootstrap/bootstrap-tab.js'),
				array('bootstrap/bootstrap-tooltip.js'),
				array('bootstrap/bootstrap-popover.js'),
				array('bootstrap/bootstrap-button.js'),
				array('bootstrap/bootstrap-collapse.js'),
				array('bootstrap/bootstrap-carousel.js'),
				array('bootstrap/bootstrap-typeahead.js'),
				array('bootstrap/bootstrap-tour.js'),
				array('bootstrap/jquery.cookie.js'),
				array('bootstrap/fullcalendar.min.js'),
				array('bootstrap/jquery.dataTables.min.js'),
				/** chart libraries **/
				array('bootstrap/excanvas.js'),
				array('bootstrap/jquery.flot.min.js'),
				array('bootstrap/jquery.flot.pie.min.js'),
				array('bootstrap/jquery.flot.stack.js'),
				array('bootstrap/jquery.flot.resize.min.js'),

				array('bootstrap/jquery.chosen.min.js'),
				array('bootstrap/jquery.uniform.min.js'),
				array('bootstrap/jquery.colorbox.min.js'),
				array('bootstrap/jquery.cleditor.min.js'),
				array('bootstrap/jquery.noty.js'),
				array('bootstrap/jquery.elfinder.min.js'),
				array('bootstrap/jquery.raty.min.js'),
				array('bootstrap/jquery.iphone.toggle.js'),
				array('bootstrap/jquery.autogrow-textarea.js'),
				array('bootstrap/jquery.uploadify-3.1.min.js'),
				array('bootstrap/jquery.history.js'),
				array('bootstrap/charisma.js'),
		));

		$this->load->model("empleados_model");
		if($this->empleados_model->checkSession()){
			// $this->empleados_model->excepcion_privilegio = $this->excepcion_privilegio;
			// $this->info_empleado = $this->empleados_model->getInfoEmpleado($_SESSION['id_empleado'], true);
			$this->{$method}();
		}else
			redirect(base_url('panel/home/'));
	}

	public function index()
	{
		$this->carabiner->js(array(
			array('general/msgbox.js')
		));

		$params['seo'] = array(
			'titulo' => 'Administración de artículos'
		);

		$sql_res = $this->db->select("id_tipo, nombre")
												->from("articulos_tipo")
												->order_by("nombre ASC")
												->get();
		$params['tipos_articulos'] = $sql_res->result();

		$this->load->model('articulos_model');
		$params['articulos'] = $this->articulos_model->get_articulos();

		if (isset($_GET['msg']))
			$params['frm_errors'] = $this->showMsgs($_GET['msg']);

		$this->load->view('panel/header', $params);
		$this->load->view('panel/general/menu', $params);
		$this->load->view('panel/articulos/admin', $params);
		$this->load->view('panel/footer');
	}

	/*
 	|	Muestra el Formulario para agregar un articulo
 	*/
	public function agregar()
	{
    $this->carabiner->css(array(
      array('libs/imgareaselect-default.css', 'screen')
    ));

		$this->carabiner->js(array(
      array('libs/jquery.form.js'),
      array('libs/jquery.imgareaselect.pack.js'),
      array('libs/ckeditor1/ckeditor.js'),
      array('panel/articulos/jquery.form.config.js'),
			array('panel/articulos/articulos.js')
		));

		$params['seo'] = array(
			'titulo' => 'Agregar Artículo'
		);
		$params['opcmenu_active'] = 'Articulos'; //activa la opcion del menu

		$this->config_add_articulo();
		if ($this->form_validation->run() == FALSE)
		{
			$params['frm_errors'] = $this->showMsgs(2, preg_replace("[\n|\r|\n\r]", '', validation_errors()));
		}
		else
		{
			$this->load->model('articulos_model');
			$res_mdl = $this->articulos_model->agrega_articulo();

			if(is_array($res_mdl))
				$params['frm_errors'] = $this->showMsgs(2, preg_replace("[\n|\r|\n\r]", '', $res_mdl["msg"]));
			else
				redirect(base_url('panel/articulos/agregar/?'.String::getVarsLink(array('msg')).'&msg=3'));
		}

		$sql_res = $this->db->select("id_tipo, nombre")
												->from("articulos_tipo")
												->order_by("nombre ASC")
												->get();
		$params['tipos_articulos'] = $sql_res->result();

    $params['inputs_hidden_path'] = '';
    if (isset($_POST['path_fimagen1'])) {
      $params['inputs_hidden_path'] .= '<input type="hidden" name="path_fimagen1" value="'.$_POST['path_fimagen1'].'" id="path_fimagen1" />';
    }

     if (isset($_POST['path_fimagen2'])) {
      $params['inputs_hidden_path'] .= '<input type="hidden" name="path_fimagen2" value="'.$_POST['path_fimagen2'].'" id="path_fimagen2" />';
    }

     if (isset($_POST['path_fimagen3'])) {
      $params['inputs_hidden_path'] .= '<input type="hidden" name="path_fimagen3" value="'.$_POST['path_fimagen3'].'" id="path_fimagen3" />';
    }



		if (isset($_GET['msg']))
			$params['frm_errors'] = $this->showMsgs($_GET['msg']);

		$this->load->view('panel/header', $params);
		$this->load->view('panel/general/menu', $params);
		$this->load->view('panel/articulos/agregar', $params);
		$this->load->view('panel/footer');
	}

	/*
 	|	Muestra el Formulario para modificar un articulo
 	*/
	public function modificar()
	{
		if (isset($_GET['id']))
		{
      $this->carabiner->css(array(
        array('libs/imgareaselect-default.css', 'screen')
      ));

			$this->carabiner->js(array(
        array('libs/jquery.form.js'),
        array('libs/jquery.imgareaselect.pack.js'),
        array('libs/ckeditor1/ckeditor.js'),
        array('panel/articulos/jquery.form.config.js'),
				array('panel/articulos/articulos.js')
			));

			$this->load->model('articulos_model');

			$params['seo'] = array(
				'titulo' => 'Modificar Artículo'
			);
			$params['opcmenu_active'] = 'Articulos'; //activa la opcion del menu

			$this->config_add_articulo('modificar');
			if ($this->form_validation->run() == FALSE)
			{
				$params['frm_errors'] = $this->showMsgs(2, preg_replace("[\n|\r|\n\r]", '', validation_errors()));
			}
			else
			{
				$res_mdl = $this->articulos_model->modificar_articulo();

				if(is_array($res_mdl))
					$params['frm_errors'] = $this->showMsgs(2, preg_replace("[\n|\r|\n\r]", '', $res_mdl["msg"]));
				else
					redirect(base_url('panel/articulos/modificar/?'.String::getVarsLink(array('msg')).'&msg=4'));
			}

			$sql_res = $this->db->select("id_tipo, nombre")
													->from("articulos_tipo")
													->order_by("nombre ASC")
													->get();
			$params['tipos_articulos'] = $sql_res->result();
			$params['data'] = $this->articulos_model->get_articulo_info();

			if (isset($_GET['msg']))
				$params['frm_errors'] = $this->showMsgs($_GET['msg']);

			$this->load->view('panel/header', $params);
			$this->load->view('panel/general/menu', $params);
			$this->load->view('panel/articulos/modificar', $params);
			$this->load->view('panel/footer');
		}
		else
			redirect(base_url('panel/articulos/?'.String::getVarsLink(array('msg')).'&msg=1'));
	}

	/*
 	|	Elimina un articulo
 	*/
	public function eliminar()
	{
		if (isset($_GET['id']))
		{
			$this->load->model('articulos_model');
			$res_mdl = $this->articulos_model->eliminar_articulo();
			if($res_mdl)
				redirect(base_url('panel/articulos/?'.String::getVarsLink(array('msg')).'&msg=5'));
		}
		else
			redirect(base_url('panel/articulos/?'.String::getVarsLink(array('msg')).'&msg=1'));
	}

	/*
 	|	Activa un articulo
 	*/
	public function activar()
	{
		if (isset($_GET['id']))
		{
			$this->load->model('articulos_model');
			$res_mdl = $this->articulos_model->activar_articulo();
			if($res_mdl)
				redirect(base_url('panel/articulos/?'.String::getVarsLink(array('msg')).'&msg=6'));
		}
		else
			redirect(base_url('panel/articulos/?'.String::getVarsLink(array('msg')).'&msg=1'));
	}

	/*
 	|	Asigna las reglas para validar un articulo al agregarlo
 	*/
	public function config_add_articulo($accion='agregar')
	{
		$this->load->library('form_validation');
		$rules = array(
							array('field' => 'ftipo_articulo',
										'label' => 'Tipo de artículos',
										'rules' => 'required|is_natural'), //
							array('field' => 'fnumero',
										'label' => 'Numero',
										'rules' => 'required|is_natural'), //
							array('field' => 'ftitulo',
										'label' => 'Título',
										'rules' => 'required|max_length[150]'), //
							array('field' => 'fparrafo1',
										'label' => 'Introducción',
										'rules' => 'required'),
							array('field' => 'fparrafo2',
										'label' => 'Contenido',
										'rules' => ''),
							array('field' => 'ffecha_publicacion',
										'label' => 'Fecha de publicación',
										'rules' => 'required|max_length[10]|callback_isValidDate') //
		);

		if ($accion == 'agregar') {
			// Valida si selecciono el archivo (PDF)
			if (isset($_FILES['farchivo']))
			{
				if ($_FILES['farchivo']['name'] == '')
				{
					$rules[] = array('field' => 'farchivo',
														'label' => 'Seleccionar artículo',
														'rules' => 'required'); //
				}
			}

			if (isset($_POST['ftipo_articulo']))
			{
				if ($_POST['ftipo_articulo'] == 3) // base de datos
				{
					if ($_FILES['farchivo_muestra']['name'] == ''){
						$rules[] = array('field' => 'farchivo_muestra',
														'label' => 'Seleccionar artículo de muestra',
														'rules' => 'required'); //
					}
				}
			}
		}

		if (isset($_FILES['fimagen1']))
		{
			if ($_FILES['fimagen1']['name'] == '')
			{
				$rules[] = array('field' => 'fimagen1',
													'label' => 'Imagen1',
													'rules' => ''); //required
			}
		}

		if (isset($_FILES['fimagen2']))
		{
			if ($_FILES['fimagen2']['name'] == '')
			{
				$rules[] = array('field' => 'fimagen2',
													'label' => 'Imagen2',
													'rules' => ''); //required
			}
		}

		if (isset($_FILES['fimagen3']))
		{
			if ($_FILES['fimagen3']['name'] == '')
			{
				$rules[] = array('field' => 'fimagen3',
													'label' => 'Imagen3',
													'rules' => ''); //required
			}
		}

		if (isset($_POST['ftipo_articulo']))
		{
			if ($_POST['ftipo_articulo'] == 1) // breviarios
			{
				$rules[] = array('field' => 'fmateria',
													'label' => 'Materia',
													'rules' => '');
			}
			elseif ($_POST['ftipo_articulo'] == 3)  // base de datos
			{
				$rules[] = array('field' => 'fformato',
													'label' => 'Formato',
													'rules' => '');

				$rules[] = array('field' => 'fvariables',
													'label' => 'Variables',
													'rules' => '');
			}
		}

		$this->form_validation->set_rules($rules);
	}

	/*
	 | Form_validation: Valida su una fecha esta en formato correcto
	 */
	public function isValidDate($str)
	{
		if($str != ''){
			if(String::isValidDate($str) == false){
				$this->form_validation->set_message('isValidDate', 'El campo %s no es una fecha valida');
				return false;
			}
		}
		return true;
	}

	/*
 	|	AJAX
 	| Metodo llamado desde ajax para obtener el siguiente numero de un tipo de
 	|	articulo
 	*/
	public function ajax_get_siguiente_numero()
	{
		$this->load->model('articulos_model');
		$res_mdl = $this->articulos_model->ajax_get_siguiente_numero();
		echo $res_mdl;
	}

  public function upload_img()
  {

    $this->load->library('my_upload');
    $this->load->model('articulos_model');

    ini_set('memory_limit', '64M');

    $path_bdd        = 'bdd/';
    $path_breviarios = 'breviarios/';
    $path_capp       = 'cappr/';

    $path_imgs       = 'images/';

    switch ($_POST['ftipo_articulo']) {
      case 1:
        $path = $path_breviarios;
        break;
      case 2:
        $path = $path_capp;
        break;
      default:
        $path = $path_bdd;
        break;
    }

    $path_anio = $this->articulos_model->validaDir('anio', $path_imgs, $path);
    $path_mes = $this->articulos_model->validaDir('mes', $path_imgs, $path.$path_anio.'/');

    $config_upload = array(
       'upload_path'     => APPPATH.$path_imgs.'articulos/'.$path.$path_anio.'/'.$path_mes,
       'allowed_types'   => '*',
       'max_size'        => '2048',
       'encrypt_name'    => TRUE
     );

    $config_resize = array(
       'image_library' => 'gd2',
       'source_image'  => '',
       'width'         => '800',
       'height'        => '600',
       'maintain_ratio' => FALSE
     );

    $this->my_upload->initialize($config_upload);
    $this->my_upload->do_resize = TRUE;
    $this->my_upload->config_resize = $config_resize;
    $data_img = $this->my_upload->do_upload($_POST['cualimg']);

    if (isset($data_img['full_path']))
    {
      echo json_encode(array('status'=>1, 'resp'=>$data_img['full_path']));
    }
    else
    {
      echo json_encode(array('status'=>0, 'resp'=>'Error: El peso de la imagen seleccionada es mayor al permitido.', 'element'=>$_POST['cualimg']));
    }
  }

  public function ajax_crop_img()
  {
    $this->load->library('my_upload');

    $_POST['w'] = round(($_POST['w'] * 800) / 500);
    $_POST['h'] = round(($_POST['h'] * 600) / 500);

    $_POST['x1'] = round(($_POST['x1'] * 800) / 500);
    $_POST['y1'] = round(($_POST['y1'] * 600) / 500);

// var_dump($_POST);

    $config_crop = array('width'  => $_POST['w'],
                         'height' => $_POST['h'],
                         'x'      => $_POST['x1'],
                         'y'      => $_POST['y1']);

// var_dump($config_crop);

    $crop_img = $this->my_upload->crop_image($_POST['path'], $_POST['path'], $_POST['w'], $_POST['h'], $config_crop);
    echo 1;
  }


  public function facebook()
  {
    if (isset($_GET['id']{0}))
    {
      $this->load->model('articulos_model');
      $id_publicacion = $this->articulos_model->publica_facebook($_GET['id']);

      if ($id_publicacion)
        redirect(base_url('panel/articulos/agregar/?'.String::getVarsLink(array('msg')).'&msg=3'));
    }
  }

	/**
	 * Muestra mensajes cuando se realiza alguna accion
	 * @param unknown_type $tipo
	 * @param unknown_type $msg
	 * @param unknown_type $title
	 */
	private function showMsgs($tipo, $msg='', $title='Articulos')
	{
		switch($tipo){
			case 1:
				$txt = 'El campo ID es requerido.';
				$icono = 'error';
				break;
			case 2: //Cuendo se valida con form_validation
				$txt = $msg;
				$icono = 'error';
				break;
			case 3:
				$txt = 'El artículo se agregó correctamente.';
				$icono = 'success';
				break;
			case 4:
				$txt = 'El artículo se modificó correctamente.';
				$icono = 'success';
				break;
			case 5:
				$txt = 'El artículo se eliminó correctamente.';
				$icono = 'success';
				break;
			case 6:
				$txt = 'El artículo se activó correctamente.';
				$icono = 'success';
				break;
		}

		return array(
				'title' => $title,
				'msg' => $txt,
				'ico' => $icono);
	}

}

/* End of file articulos.php */
/* Location: ./application/controllers/panel/articulos.php */
